﻿using System;
using System.Collections.Generic;
using System.Linq;
using Model.Permission;
using Service.Permission;
using SqlHelper;
using System.Transactions;
using Utils.Log;
using Utils.Types;

namespace Service.Admin
{
    public class UserInfoService : Repository<Model.Admin.UserInfo>
    {
        public int CreateUser(Model.Admin.UserInfo user)
        {
            int userid;

            try
            {
                user.CreateTime = user.UpdateTime = DateTime.Now;
                user.IsDelete = 0;
                user.IsLock = 0;

                if (user.PassWords.NoNullOrEmpty())
                    user.PassWords = Utils.PassWord.MD5.Encrypt32Bit(user.PassWords);

                UserTypeService usertypeservice = new UserTypeService();
                MenuService menuservice = new MenuService();

                var menulistid = usertypeservice.GetEntityByObject<Model.Admin.UserType>(new { TypeID = user.UserType });  //查询usertype相关拥有的menu ids
                var hasmenulist = menuservice.HasMenus(menulistid.HasMenuID);         //根据ids 查询有权限menu集合
                var nohasmenulist = menuservice.NoHasMenus(menulistid.HasMenuID);     //根据ids 查询无权限menu集合

                List<UserMenu> usermenulist = new List<UserMenu>();
                usermenulist.AddRange(hasmenulist.Select(item => new UserMenu { HasPermission = 1, MenuID = item.MenuID }));   //创建usermenu对象 用于创建菜单权限所用
                usermenulist.AddRange(nohasmenulist.Select(item => new UserMenu { HasPermission =0, MenuID = item.MenuID }));   //创建usermenu对象 用于创建菜单权限所用
                
                using (TransactionScope trans = new TransactionScope())
                { 
                    userid = Insert(user);
                    UserMenuService usermenuservice = new UserMenuService();
                    bool status = usermenuservice.UpdateTree(usermenulist, userid);
                    if (userid > 0 && status)
                        trans.Complete();
                }
            }
            catch (Exception e)
            {
                userid = 0;
                Log.Txt("创建用户失败：\r\n" + e, LogType.Error);
            }
            return userid;
        }

    }
}
